package com.ilxqx.framework.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.output.StringBuilderWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Writer;

/**
 * 模板处理工具类
 * @author venus
 */
@Slf4j
@Component
public final class TemplateUtils {

    /**
     * Freemarker模板引擎配置类
     */
    private static Configuration configuration;

    @Autowired
    public TemplateUtils(Configuration configuration) {
        configuration.setOutputEncoding("UTF-8");
        configuration.setDefaultEncoding("UTF-8");
        configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
        configuration.setDateFormat("yyy-MM-dd");
        configuration.setTimeFormat("HH:mm:ss");
        configuration.setBooleanFormat("true,false");
        TemplateUtils.configuration = configuration;
    }

    /**
     * 解析一个模板
     * @param templatePath 模板路径
     * @param data 模板数据
     * @param writer 输出Writer
     * @throws IOException IO异常
     * @throws TemplateException 模板解析异常
     */
    public static void render(@NonNull String templatePath, Object data, @NonNull Writer writer) throws IOException, TemplateException {
        Template template = configuration.getTemplate(templatePath, "UTF-8");
        template.process(data, writer);
    }

    /**
     * 解析一个模板为字符串
     * @param templatePath 模板路径
     * @param data 模板数据
     * @return 解析后的字符串
     */
    public static String renderToString(@NonNull String templatePath, Object data) {
        StringBuilderWriter writer = new StringBuilderWriter();
        try {
            TemplateUtils.render(templatePath, data, writer);
            return writer.toString();
        } catch (IOException | TemplateException e) {
            log.warn("解析模板为字符串时出现错误：{}", e);
        }
        return "";
    }

}
